//
//  PasswordLoginLogic.swift
//  Casecord
//
//  Created by baozi on 2024/1/4.
//

import Foundation
class PwdInputToLoginLogic: BaseLogic {
    var router: Router?
    var type: SignType = .password_login
    
    func toNext(
        areaCode: String,
        phone: String,
        password: String
    ) {
        switch type {
        case .password_login:
            Task {
                do {
                    let result = try await LoginAPI
                        .login(
                            loginFrom: .type_password_2,
                            loginType: .type_phone_0,
                            areaCode: areaCode,
                            phoneNumber: phone,
                            password: password
                        )
                        .make()
                        .async(disposeBag: self.disposeBag)
                    await UserService.shared.login(result)
                } catch {
                    await ToastManager.show(text: error.errorMessage)
                }
            }
        case .password_set:
            Task {
                do {
                    let _ = try await LoginAPI
                        .smsSend(
                            areaCode: areaCode,
                            phone: phone,
                            smsType: "REGISTER"
                        )
                        .make()
                        .async(disposeBag: self.disposeBag)
                    await router?.to(name: .smscodeLogin(phone: phone, areaCode: areaCode, signType: .password_set, password: password))
                } catch {
                    await ToastManager.show(text: error.errorMessage)
                }
            }
        case .phone_bind:
            break
        }
    }
    
    func toVerifyCodeLogin(
        areaCode: String,
        phone: String
    ) {
        Task {
            do {
                let _ = try await LoginAPI
                    .smsSend(
                        areaCode: areaCode,
                        phone: phone,
                        smsType: "LOGIN"
                    )
                    .make()
                    .async(disposeBag: self.disposeBag)
                await router?.to(name: .smscodeLogin(phone: phone, areaCode: areaCode, signType: .password_login, password: nil))
            } catch {
                await ToastManager.show(text: error.errorMessage)
            }
        }
    }
    /// 密码登录
    /// - Parameters:
    ///   - phone:
    ///   - password:
    func login(
        areaCode: String,
        phone: String,
        password: String
    ) async throws -> APIResult {
        return try await LoginAPI
            .login(
                loginFrom: .type_password_2, loginType: .type_phone_0,
                areaCode: areaCode,
                phoneNumber: phone,
                password: password
            )
            .make()
            .async(disposeBag: self.disposeBag)
    }
}
